package com.demo.quartz;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class TestJobExecution {
    private static Logger logger = LoggerFactory.getLogger(TestJobExecution.class);
    private Scheduler scheduler;

    public void createQuartz() throws InterruptedException {
        StdSchedulerFactory stdSchedulerFactory = new StdSchedulerFactory();
        logger.info("start createQuartz.....");
        int i = 0;
        int leader = 1;
        while (true) {
            Thread.sleep(2000);
            if (leader==1) {
                try {
                    scheduler = stdSchedulerFactory.getScheduler();
                    JobDetail jobDetail = JobBuilder.newJob(TestJobExecutionTime.class)
                            .withIdentity("job"+i, "gp1"+i)
                            .build();

                    Trigger trigger = TriggerBuilder.newTrigger()
                            .withIdentity("trigger"+i, "gp1"+i)
                            .withSchedule(CronScheduleBuilder.cronSchedule("0/10 * * * * ?"))
                            .build();

                    scheduler.scheduleJob(jobDetail, trigger);
                    logger.info("scheduler start...........");
                    scheduler.start();
                } catch (SchedulerException e) {
                    e.printStackTrace();
                }
            } else {
                logger.info("this is not leader");
                if (scheduler != null) {
                    try {
                        if (!scheduler.isShutdown()) {
                            scheduler.shutdown();
                        }
                    } catch (SchedulerException e) {
                        e.printStackTrace();
                    } finally {
                        scheduler = null;
                    }
                }
            }
            i++;

            if (i == 30)
            {
                leader = 0;
            }
        }
    }
}
